import { getCurrentInstance } from 'vue'
import { useTagsViewStore } from '@/store/tagsView'
import { useRoute, useRouter } from 'vue-router'

export function useTagsView() {
  const instance = getCurrentInstance()
  const tagsViewStore = useTagsViewStore()
  const route = useRoute()
  const router = useRouter()
  
  /**
   * 关闭当前标签
   * @param {Object} view 视图对象，默认为当前路由
   */
  const closeSelectedTag = (view = route) => {
    // 首先检查是否是首页标签，如果是则不关闭
    if (view.path === '/dashboard') {
      return Promise.resolve()
    }
    
    // 关闭标签并处理导航
    return tagsViewStore.delView(view).then(({ visitedViews }) => {
      if (isActive(view)) {
        toLastView(visitedViews, view)
      }
    })
  }
  
  /**
   * 关闭其他标签
   * @param {Object} view 视图对象，默认为当前路由
   */
  const closeOthersTags = (view = route) => {
    router.push(view)
    return tagsViewStore.delOthersViews(view)
  }
  
  /**
   * 关闭所有标签
   */
  const closeAllTags = () => {
    return tagsViewStore.delAllViews().then(({ visitedViews }) => {
      console.log('Store中关闭所有标签完成，剩余:', visitedViews.length)
      // 关闭所有标签后跳转到首页
      router.push('/dashboard')
      return { visitedViews }
    })
  }
  
  /**
   * 刷新当前标签
   * @param {Object} view 视图对象，默认为当前路由
   */
  const refreshSelectedTag = (view = route) => {
    tagsViewStore.delCachedView(view).then(() => {
      const { fullPath } = view
      router.replace({
        path: '/redirect' + fullPath
      })
    })
  }
  
  /**
   * 判断是否是激活状态
   * @param {Object} view 视图对象
   * @returns {Boolean}
   */
  const isActive = (view) => {
    // 使用fullPath或path进行匹配
    return view.fullPath === route.fullPath || (view.path === route.path && !view.fullPath)
  }
  
  /**
   * 跳转到最后一个视图
   * @param {Array} visitedViews 已访问视图列表
   * @param {Object} view 当前视图
   */
  const toLastView = (visitedViews, view) => {
    const latestView = visitedViews.slice(-1)[0]
    if (latestView) {
      router.push(latestView.path)
    } else {
      // 如果没有标签，则跳转到首页
      if (view.name === 'Dashboard') {
        router.replace({ path: '/redirect' + view.path })
      } else {
        router.push('/')
      }
    }
  }
  
  /**
   * 添加标签
   * @param {Object} view 视图对象，默认为当前路由
   */
  const addTag = (view = route) => {
    const { name } = view
    if (name) {
      tagsViewStore.addView(view)
    }
    return false
  }
  
  return {
    visitedViews: tagsViewStore.visitedViews,
    cachedViews: tagsViewStore.cachedViews,
    closeSelectedTag,
    closeOthersTags,
    closeAllTags,
    refreshSelectedTag,
    isActive,
    toLastView,
    addTag
  }
}